package com.glory.brepda.activity.lanjian;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.glory.brepda.activity.mfg.BreLanjianPasteBarCodeWGOutPutActivity;
import com.glory.brepda.adapter.CheckG028ListAdapter;
import com.glory.brepda.base.BaseActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.recyclerview.widget.RecyclerView;
import com.glory.brepda.R;
import com.glory.brepda.base.Constant;
import com.glory.brepda.entity.LotAndPackagingfileEntity;
import com.glory.brepda.entity.LotInfoEntity;
import com.glory.brepda.entity.response.BaseResponseBean;
import com.glory.brepda.utils.NetUtils;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.model.Response;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_DialogEntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_EntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.view.FreeUI_ClearEditText;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import butterknife.BindView;
import butterknife.OnClick;

public class SfcInnerLabelMainActivity extends BaseActivity {

        @BindView(R.id.tvTitle)
        TextView tvTitle;
        @BindView(R.id.llMain)
        LinearLayout llMain;
        @BindView(R.id.tvBaseSubmit)
        TextView tvBaseSubmit;
        @BindView(R.id.tvClear)
        TextView tvClear;
        @BindView(R.id.tvReset)
        TextView tvReset;
        @BindView(R.id.reel)
        EditText reel;
        @BindView(R.id.rvcheckReelList)
        RecyclerView rvcheckReelList;
        @BindView(R.id.etUserName)
        FreeUI_ClearEditText etUserName;
        @BindView(R.id.etLot)
        FreeUI_ClearEditText etLot;
        @BindView(R.id.etProductName)
        FreeUI_ClearEditText etProductName;
        @BindView(R.id.etCode)
        FreeUI_ClearEditText etCode;
        @BindView(R.id.etMainQty)
        FreeUI_ClearEditText etMainQty;
        @BindView(R.id.etMainQtyNum)
        FreeUI_ClearEditText etMainQtyNum;
        @BindView(R.id.etBaseReel)
        FreeUI_ClearEditText etBaseReel;

        private CheckG028ListAdapter mAdapter;
        private LotInfoEntity lotInfoEntity;
        private LotAndPackagingfileEntity entity;

        public static String LOT = "";
        public static String PRODUCT = "";;
        public static String CODE = "";;

        private int mainQty=0,baseQty=0,upQty=0;

    @Override
        protected int getLayoutResId() {
        return R.layout.activity_sfc_inner_label_main;
    }

        @Override
        protected void initView() {

        tvBaseSubmit.setText("提交数据");
//        String title = getIntent().getStringExtra(FreeApi_StaticMembers.SHOW_PLUGIN_KEY);
//        tvTitle.setText(title);
        tvReset.setVisibility(View.VISIBLE);
        tvReset.setText("清除最新列");
        tvClear.setVisibility(View.VISIBLE);
        tvClear.setText("清除全部");
        setMainLayout(llMain);
        //reel
        initRecyclerView(rvcheckReelList,this);
        mAdapter = new CheckG028ListAdapter(null);
        mAdapter.isFirstOnly(true);
        mAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        rvcheckReelList.setAdapter(mAdapter);

        reel.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {

                String text = editable.toString();
                if(StringUtils.isNotEmpty(text) && text.contains("/") && text.split("/").length >=3){
                    // 序号重复问题
                    List<String> dates = mAdapter.getData();
//                    if(dates.size() !=0){
//                        for(String item : dates){
//                            // 重复序号
//                            if(item.split("/")[2].equals(text.split("/")[2])){
//                                showToast("序号"+text.split("/")[2]+"重复请检查!",false);
//                                break;
//                            }
//                        }
//                    }

                    if(getText(etLot).equals("") || getText(etUserName).equals("")){
                        showToast("请先扫描批次工号!",false);
                    }else{

                        if(dates.size() >= upQty){
                            showToast("超过最大值录入条数！无法录入！最大条数为 批次数/盘基数 向上取整："+upQty,false);
                        }else{

                            // 有校验码跟无校验码不能混淆
                            String[] arrs = text.split("/");
                            List<String> listOk = new ArrayList<>();
                            for (String str : arrs) {
                                if (!str.isEmpty()) {
                                    listOk.add(str);
                                }
                            }

                            if((CODE.equals("")  &&  listOk.size() == 4) || (!CODE.equals("")  &&  listOk.size() == 3) ){
                                showToast("有校验码和无校验码混淆！请检查",false);
                            }else{
                                mAdapter.addData(text);
                                if(dates.size() !=0){
                                    int sum = dates.size()* Integer.parseInt(etBaseReel.getText().toString());
                                    etMainQtyNum.setText(String.valueOf(sum));
                                }
                                reel.requestFocus();
                            }
                        }
                    }
                    reel.setText("");
                }
            }
        });

//            initEdit(etLot, s -> {
//                //获取lot信息
//                LotUtils.searchLotInfo(SfcInnerLabelMainActivity.this, s, getSupportFragmentManager(), new LotUtils.netCallback<LotInfoEntity>() {
//                    @Override
//                    public void onSuccess(LotInfoEntity body) {
//                        lotInfoEntity = body;
//                        if(!body.getLOT().getCUSTOMERCODE().equals("G028")){
//                            showToast("非G028的管，无法使用该界面功能!",true);
//                        }
//                        LOT = getText(etLot);
//                        etMainQty.setText(body.getLOT().getMAINQTY());
//                        if(StringUtils.isNotEmpty(body.getLOT().getUDF().getProductModel())){
//                            etProductName.setText(body.getLOT().getUDF().getProductModel());
//                            PRODUCT = body.getLOT().getUDF().getProductModel();
//                        }
//                        if(StringUtils.isNotEmpty(body.getWORKORDER().getUDF().getLblSpecial3())){
//                            etCode.setText(body.getWORKORDER().getUDF().getLblSpecial3());
//                            CODE = body.getWORKORDER().getUDF().getLblSpecial3();
//                        }
//                        if (!body.getSHOWMSG().equals("")) {
//                            showConfirmDialog(body.getSHOWMSG());
//                        }
//                    }
//
//                    @Override
//                    public void onFail(Throwable t) {
//                        loadError(t, "LOTQUERY");
//                    }
//
//                });
//            });

            initEdit(etLot, sa -> {
                //获取lot信息
                FreeUI_EntityCallBack<BaseResponseBean<LotAndPackagingfileEntity>> callBack = new FreeUI_DialogEntityCallBack<BaseResponseBean<LotAndPackagingfileEntity>>
                        (new TypeToken<BaseResponseBean<LotAndPackagingfileEntity>>() {
                        }.getType(), getSupportFragmentManager(), this) {

                    @Override
                    public void onSuccess(Response<BaseResponseBean<LotAndPackagingfileEntity>> response) {
                        super.onSuccess(response);
                        if (response.body().isSuccess(getApplicationContext(), true, getSupportFragmentManager())) {
                            entity = response.body().getResponse().getBody();
//                            lotInfoEntity = body;
//                        if(!entity.getLOT().getCUSTOMERCODE().equals("G028")){
//                            showToast("非G028的管，无法使用该界面功能!",true);
//                        }
                        LOT = getText(etLot);
                        etMainQty.setText(entity.getLOT().getMAINQTY());
                        if(StringUtils.isNotEmpty(entity.getLOT().getUDF().getProductModel())){
                            etProductName.setText(entity.getLOT().getUDF().getProductModel());
                            PRODUCT = entity.getLOT().getUDF().getProductModel();
                        }
                        if(StringUtils.isNotEmpty(entity.getWO().getUDF().getLblSpecial3())){
                            etCode.setText(entity.getWO().getUDF().getLblSpecial3());
                            CODE = entity.getWO().getUDF().getLblSpecial3();
                        }
                        if(StringUtils.isNotEmpty(entity.getPACKS().getReelNum())){
                            etBaseReel.setText(entity.getPACKS().getReelNum());
                        }
                            // 超过累计数不纳入计算
                            mainQty = Integer.parseInt(etMainQty.getText().toString());
                            baseQty = Integer.parseInt(etBaseReel.getText().toString());
                            upQty  = (int) Math.ceil(mainQty * 1.0 / baseQty);

                            reel.requestFocus();
                        }
                    }

                    @Override
                    public void onError(Response<BaseResponseBean<LotAndPackagingfileEntity>> response) {
                        super.onError(response);
                        loadError(response.getException(), "失败");
                    }
                };
                JsonObject map = new JsonObject();
                map.addProperty("LOT_ID", getText(etLot));
                map.addProperty("ACTION_TYPE", "QUERY");
                NetUtils.requestPostNet("IF.PDA_QUERY_LOT_PACKS", "Common", getApplication(), map, callBack);
            });
    }

        @Override
        protected void initData() {

    }

        @OnClick({R.id.tvBaseSubmit,R.id.tvReset,R.id.tvClear})
        public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tvBaseSubmit:
                List<String> dates = mAdapter.getData();
                submit(dates);
                break;
            case R.id.tvReset:
                int n = mAdapter.getData().size();
                if(n!=0){
                    mAdapter.remove(n-1);
                    int basereel = Integer.parseInt(etBaseReel.getText().toString());
                    int sum = Integer.parseInt(etMainQtyNum.getText().toString());
                    etMainQtyNum.setText(String.valueOf(sum - basereel));
                }
                break;
            case R.id.tvClear:
                mAdapter.getData().clear();
                mAdapter.notifyDataSetChanged();
                clearAll();
                break;
        }
    }

    private void submit(List<String> dates){

        if(dates.size() == 0 || StringUtils.isEmpty(etUserName.getText()) || StringUtils.isEmpty(etLot.getText())){
            return;
        }
        // 校验数据列准确性 批号，型号，校验码必须全部一样。序号必须全部不一样 否则不能通过
        boolean ok = checkInfo(dates);
        if(!ok){
            return;
        }

        FreeUI_EntityCallBack<BaseResponseBean<JSONObject>> callBack = new FreeUI_DialogEntityCallBack<BaseResponseBean<JSONObject>>
                (new TypeToken<BaseResponseBean<JSONObject>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess(Response<BaseResponseBean<JSONObject>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(getApplicationContext(), true, getSupportFragmentManager())) {
                    showToast("成功", true);
                    clearAll();
                }
            }

            @Override
            public void onError(Response<BaseResponseBean<JSONObject>> response) {
                super.onError(response);
                loadError(response.getException(), "PDA_SFC_INNER_LABEL");
            }
        };
        JsonObject map = new JsonObject();
        map.addProperty("NAME", getText(etUserName));
        map.addProperty("LOT_ID", getText(etLot));
        map.addProperty("MAIN_QTY", getText(etMainQty));
        map.addProperty("PRODUCT_MODEL", getText(etProductName));
        map.addProperty("CODE", getText(etCode));
        map.addProperty("BASE_REEL", getText(etBaseReel));
        map.addProperty("LABEL_NUM", upQty);
        String info = dates.toString();
        map.addProperty("LABEL_INFO", info.substring(1, info.length()-1));
        map.addProperty("ACTION","SFC_LABEL");
        NetUtils.requestPostNet("IF.PDA_SFC_INNER_LABEL", "Common", SfcInnerLabelMainActivity.this, map, callBack);

    }

    private boolean checkInfo(List<String> dates) {

        // 数据列必须跟批次总数对应得上
        if(dates.size() != upQty){
            showToast("扫描的列数据不能少于批次总数，需要扫："+upQty+"条数据才能提交", true);
            return false;
        }
        // 校验数据列准确性 批号，型号，校验码必须全部一样。序号必须全部不一样 否则不能通过
        boolean flag = true;
        if(dates.size() >= 1){

//            String firstDate = dates.get(0);
//            String[] split = firstDate.split("/");
//            String firstLot = getText(etLot),firstProduct = getText(etProductName),firstCode = getText(etCode);;
//
//            for (int i = 0; i < dates.size(); i++) {
//                // 批次 型号
//                if(!dates.get(i).contains(firstLot) || !dates.get(i).contains(firstProduct)){
//                    showToast("扫描的列数据批号或型号不唯一，校验不通过", true);
//                    flag = false;
//                    break;
//                }
//            }

            Set<String> setXuhao = new HashSet<>();
            Set<String> setLot = new HashSet<>();
            setLot.add(LOT);
            Set<String> setProduct = new HashSet<>();
            setProduct.add(PRODUCT);
            Set<String> setCode = new HashSet<>();
            setCode.add(CODE);

            for(String temp : dates){
                String[] split = temp.split("/");
                setLot.add(split[0]);
                setProduct.add(split[1]);
                setXuhao.add(split[2]);
                if(split.length > 3){
                    setCode.add(split[3]);
                }else{
                    setCode.add("");
                }
            }
            if(setLot.size() > 1 || setCode.size() > 1){
                showToast("批号或校验码校验不通过,请检查", true);
                flag = false;
            }

            // 这种主要是因为主批型号跟产品型号是包含关系情况下，集合中已经有两个不一样的型号，但是属于正常情况，> 2 就是有混型号情况
            if(!getText(etProductName).equals(dates.get(0).split("/")[1]) && setProduct.size() > 2){
                showToast("型号校验不通过,请检查", true);
                flag = false;
            }

            if(setXuhao.size() != dates.size()){
                showToast("扫描的列数据序号存在重复，校验不通过", true);
                flag = false;
            }
        }

        return flag;
    }

    public void clearAll(){
        etMainQtyNum.setText(null);
        etMainQty.setText(null);
        etProductName.setText(null);
        etUserName.setText(null);
        etCode.setText(null);
        etBaseReel.setText(null);
        etLot.setText(null);
        mainQty = 0;
        baseQty = 0;
        upQty  = 0;
        mAdapter.getData().clear();
        mAdapter.notifyDataSetChanged();
    }
}